import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_rider/api/api.dart';
import 'package:flutter_rider/event/refresh_order_event.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/main/widgets/base/number_layout.dart';
import 'package:flutter_rider/main/widgets/base/pop_pick_spu.dart';
import 'package:flutter_rider/main/widgets/base/task_layout.dart';
import 'package:flutter_rider/main/widgets/dialog/alert_dialog.dart';
import 'package:flutter_rider/main/widgets/dialog/loading_dialog.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/ext/u_title_layout.dart';
import 'package:flutter_rider/main/widgets/state/state_layout.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/module/waybill/api/waybill_api.dart';
import 'package:flutter_rider/routers/fluro_navigator.dart';
import 'package:flutter_rider/utils/log.dart';
import 'package:flutter_rider/utils/open_utils.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_rider/utils/tip.dart';

import '../../../utils/toast.dart';

class WaybillChangePage extends StatefulWidget {
  //之前修改的记录
  dynamic selectDataInfo;
  WaybillChangePage(this.selectDataInfo, {Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return WaybillChangePageState();
  }
}

class WaybillChangePageState extends State<WaybillChangePage> {
  dynamic _data;

  var _unitName = "";
  int _type = 1;
  List<int> _skuResults = [];

  /// spu的每项内容
  dynamic _jSkuOptions1;
  String fhUserName = "";
  String shUserName = "";
  String fhPhone = "";
  String shPhone = "";
  String fhCarPlate = "";
  String shCarPlate = "";
  String fhAddress = "";
  String shAddress = "";
  String fhLat = "";
  String shLat = "";
  String fhLng = "";
  String shLng = "";
  String fhStationName = "";
  String shStationName = "";
  String fhStationId = "";
  String shStationId = "";
  String fhAliasName = "";
  String shAliasName = "";
  int fhAliasId = 0;
  int shAliasId = 0;
  int skuProductId = 0;
  String skuProductName = "";
  String skuCode = "";
  String spuProductName = "";
  int spuProductId = 0;

  /// 选择中sku_option，包含name,code,val
  var skuOption1 = [];

  ///修改字段新增
  var _mission_num = 0;
  double _total_weight = 0;
  var _qty = 0;
  var _unit = 1;

  /// 货物类别下标
  var _categoryIndex = 0;

  /// spu的每项的下标
  var _spuKeyIndex = 0;

  /// spu的每项子项的下标
  var _spuValIndex = 0;

  final NumberLayoutController _weightLayoutController =
      NumberLayoutController(0);
  final NumberLayoutController _qtyLayoutController = NumberLayoutController(0);
  final TaskLayoutController _taskLayoutController = TaskLayoutController(0);

  @override
  void initState() {
    super.initState();
    _weightLayoutController.decimal = true;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: UIColor.color_main,
        appBar: UTitleLayout.getBackTitle(context, "货物信息"),
        body: SafeArea(
            child: StateLayout(
          url: "/waybill/sku",
          childBuilder: _renderContent,
          dataCallback: _onDataCallback,
        )));
  }

  Widget _renderContent(dynamic data) {
    return SingleChildScrollView(
        child: Column(
      children: [
        _renderSKU(),
        // 10.hspace,
        // _renderTask(),
        44.hspace,
        Padding(
          padding: EdgeInsets.all(12.rpx),
          child: UText.getBkButton(
            "提交",
            16.rpx,
            bkColor: UIColor.color_primary,
            radius: 24.rpx,
            width: double.infinity,
            height: 48.rpx,
            onPressed: _onClickSubmit,
          ),
        ),
      ],
    ));
  }

  Widget _renderSKU() {
    return Container(
      decoration: const BoxDecoration(
        color: UIColor.color_content,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _renderSpuType(),
          ..._jSkuOptions1.asMap().keys.map((index) {
            return _renderOneSku(index);
          }).toList(),
          _renderTotalWeight(),
          Container(
              margin: EdgeInsets.only(left: 16.rpx, top: 10.rpx, right: 16.rpx),
              height: 0.5.rpx,
              color: UIColor.color_divider),
          10.hspace,
          _renderQty(),
          6.hspace,
        ],
      ),
    );
  }

  Widget _renderSpuType() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: Container(
        height: 48.rpx,
        padding: EdgeInsets.symmetric(horizontal: 16.rpx),
        child: Row(
          children: [
            UText.get("货物类别", UIColor.color_t1, 16.rpx, fw: FontWeight.w600),
            const Spacer(),
            UText.get(spuProductName, UIColor.color_t1, 14.rpx),
            4.wspace,
            Icon(Icons.navigate_next, size: 20.rpx, color: UIColor.color_t3),
          ],
        ),
      ),
      onTap: () {
        // 选择货物类别
        OpenUtils.pop(
            context,
            PopPickSpu(
              list: _data,
              nameKey: "name",
              initItem: _categoryIndex,
              callback: (index) {
                setState(() {
                  _categoryIndex = index;
                  _spuKeyIndex = 0;
                  _spuValIndex = 0;
                  _unit = _data[_categoryIndex]["unit"];
                  _unitName = _data[_categoryIndex]["unit_name"];
                  skuProductId = _data[_categoryIndex]["sku_product_id"];
                  skuProductName = _data[_categoryIndex]["sku_product_name"];
                  spuProductName = _data[_categoryIndex]["name"];
                  spuProductId = _data[_categoryIndex]["id"];
                });
                _getSpuResult();
                _getSkuOption1();
                _reShowMission();
                _setSkuOptions1();
                _getSkuCode();
              },
            ));
      },
    );
  }

  Widget _renderOneSku(int index) {
    var sku = _jSkuOptions1[index];
    var list = sku["val"] as List;
    return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Container(
          margin: EdgeInsets.symmetric(horizontal: 16.rpx),
          height: 0.5.rpx,
          color: UIColor.color_divider),
      16.hspace,
      Padding(
        padding: EdgeInsets.symmetric(horizontal: 16.rpx),
        child: UText.get(sku["name"], UIColor.color_t1, 16.rpx,
            fw: FontWeight.w600),
      ),
      12.hspace,
      Padding(
        padding: EdgeInsets.symmetric(horizontal: 16.rpx),
        child: Wrap(
          spacing: 10.rpx,
          runSpacing: 0.rpx,
          children: list
              .asMap()
              .keys
              .map((valIndex) => _renderOneSkuVal(sku, index, valIndex))
              .toList(),
        ),
      ),
      16.hspace,
    ]);
  }

  Widget _renderOneSkuVal(dynamic sku, int index, int valIndex) {
    var isSelect = valIndex == _skuResults[index] - 1;
    return UText.getBkButton(
      sku["val"][valIndex],
      14.rpx,
      color: isSelect ? Colors.white : UIColor.color_t3,
      width: 50.rpx,
      height: 32.rpx,
      radius: 8.rpx,
      bkColor: isSelect ? UIColor.color_primary : UIColor.color_input,
      padding: EdgeInsets.symmetric(horizontal: 12.rpx),
      onPressed: () {
        // spu的每项子项的下标
        setState(() {
          _spuKeyIndex = index;
          _spuValIndex = valIndex;
        });
        // spu的每项子项的下标,更新选择下标的结果
        _skuResults[_spuKeyIndex] = _spuValIndex + 1;
        _getSkuOption1();
        _reShowMission();
        _setSkuOptions1();
        _getSkuCode();
      },
    );
  }

  Widget _renderTotalWeight() {
    Widget rw;
    if (_unit == 1) {
      rw = 0.wspace;
    } else {
      rw = Container(
          padding: EdgeInsets.fromLTRB(0, 10.rpx, 0, 0),
          margin: EdgeInsets.fromLTRB(16.rpx, 0, 16.rpx, 0),
          decoration: const BoxDecoration(
            border: Border(
                top: BorderSide(width: 0.5, color: UIColor.color_divider)),
          ),
          child: Row(
            children: [
              UText.get("数量（吨）", UIColor.color_t1, 16.rpx, fw: FontWeight.w600),
              const Spacer(),
              NumberLayout(
                  controller: _weightLayoutController,
                  initNumber: _total_weight,
                  max: 10000,
                  editParentText: () => {
                        setState(() {
                          //_choose = 2;
                        })
                      }),
            ],
          ));
    }
    return rw;
  }

  Widget _renderQty() {
    return Row(
      children: [
        16.wspace,
        UText.get("件数（件）", UIColor.color_t1, 16.rpx, fw: FontWeight.w600),
        const Spacer(),
        NumberLayout(
            controller: _qtyLayoutController,
            initNumber: _qty,
            max: 10000,
            editParentText: () => {_reShowMission(), _getSkuCode()}),
        16.wspace,
      ],
    );
  }

  Widget _renderTask() {
    return Container(
        height: 48.rpx,
        padding: EdgeInsets.symmetric(horizontal: 16.rpx),
        decoration: const BoxDecoration(
          color: UIColor.color_content,
        ),
        child: Row(
          children: [
            UText.get("任务数量", UIColor.color_t1, 16.rpx, fw: FontWeight.w600),
            const Spacer(),
            TaskLayout(
                controller: _taskLayoutController,
                initNumber: _total_weight,
                max: 100,
                editParentText: () => {}),
          ],
        ));
  }

  _onDataCallback(dynamic data) {
    _data = data;

    /// 选择中sku_option，包含name,code,val
    skuOption1 = jsonDecode(widget.selectDataInfo["sku_option"]);

    /// 货物类别下标
    spuProductId = widget.selectDataInfo["spu_product_id"];

    // var skuProductId = widget.selectDataInfo["sku_product_id"];

    List temp = data;

    for (var i = 0; i < temp.length; i++) {
      var tempSKU = temp[i];

      if (spuProductId == tempSKU["id"]) {
        _categoryIndex = i;
        var option1 = jsonDecode(tempSKU["option1"]);
        //option1 会用到 option3 提交会用到 思路就是 匹配option1
        print(option1);
      }

      // "option1" -> "[{"name":"商品","code":"a","val":["进口","出口"]},{"name":"运输方式","code":"b","val":["火车","空运"]},{"name":"地点","code":"c","val":["中国","俄罗…"
    }

    //下面是回显数据操作
    _qty = widget.selectDataInfo["qty"];

    // _mission_num = widget.selectDataInfo["mission_num"];
    _unit = widget.selectDataInfo["unit"];
    int weight = widget.selectDataInfo["total_weight"];

    _total_weight = _unit == 2 ? (weight / 1000) : weight.toDouble();

    _qtyLayoutController.number = _qty;

    _taskLayoutController.number = _mission_num;
    _weightLayoutController.number = _total_weight;

    _unitName = widget.selectDataInfo["unit_name"];

    spuProductName = widget.selectDataInfo["spu_product_name"];
    skuProductId = widget.selectDataInfo["sku_product_id"];
    skuProductName = widget.selectDataInfo["sku_product_name"];

    skuCode = widget.selectDataInfo["sku_code"];
    _skuResults = _parseSkuCode(skuCode);

    _getSkuOption1();
    _getSkuCode();
    _setSkuOptions1();
    _reShowMission();
  }

  List<int> _parseSkuCode(String code) {
    var begin = -1;
    var end = -1;
    List<int> skuResults = [];
    for (int i = 0; i < code.length; i++) {
      var ch = code.codeUnitAt(i);
      if (_isLetter(ch)) {
        if (begin > 0) {
          end = i;
          skuResults.add(int.parse(code.substring(begin, end)));
          begin = -1;
        }
      } else if (_isDigit(ch)) {
        if (begin == -1) {
          begin = i;
        }
      }
    }
    if (begin > 0) {
      skuResults.add(int.parse(code.substring(begin, code.length)));
    }
    skuResults.removeAt(skuResults.length - 1);
    return skuResults;
  }

  bool _isLetter(int code) {
    return code >= "a".codeUnitAt(0) && code <= "z".codeUnitAt(0);
  }

  bool _isDigit(int code) {
    return code >= "0".codeUnitAt(0) && code <= "9".codeUnitAt(0);
  }

  _getSkuOption1() {
    List<Object> skuOption1Results = [];
    var _options1 = jsonDecode(_data[_categoryIndex]["option1"]);
    for (var i = 0; i < _skuResults.length; i++) {
      // for (var j = 0; j < _options1.length; j++) {
      if (_skuResults[i] != 0) {
        skuOption1Results.add({
          "name": _options1[i]["name"].toString(),
          "code": _options1[i]["code"].toString(),
          "val": _options1[i]["val"][_skuResults[i] - 1].toString()
        });
        // }
      }
    }
    skuOption1 = skuOption1Results;
    for (var i = 0; i < skuOption1.length; i++) {
      for (var j = i + 1; j < skuOption1.length; j++) {
        if (skuOption1[i]["name"] == skuOption1[j]["name"]) {
          skuOption1.removeAt(j);
          // skuOption1.splice(j, 1);
          j--;
        }
      }
    }
    ;
  }

  /// 根据选择的项和数量来获取对应的sku
  _getSkuCode() {
    List arr = jsonDecode(_data[_categoryIndex]["option3"])["values"];
    List array = jsonDecode(_data[_categoryIndex]["option1"]);

    for (var i = 0; i < arr.length; i++) {
      int _account = 0;

      for (var z in arr[i].values) {
        for (var j = 0; j < _skuResults.length; j++) {
          if (z == array[j]["val"][_skuResults[j] - 1]) {
            _account += 1;
          }
        }
      }
      // 按件计费
      if (_unit == 1 && arr[i]["section"] != null) {
        num _qty = _qtyLayoutController.number;
        bool flag = _qty >= jsonDecode(arr[i]["section"])[0] &&
            _qty <= jsonDecode(arr[i]["section"])[1];
        if (_account == _skuResults.length && flag) {
          skuCode = arr[i]["SKU"];
        }
      } else {
        if (_account == _skuResults.length) {
          skuCode = arr[i]["SKU"];
        }
      }
    }
  }

  /// 获取选中结果下标
  _getSpuResult() {
    // 先初始化，避免脏数据
    _skuResults = [];
    List arr = jsonDecode(_data[_categoryIndex]["option1"]);
    // 根据option1的长度确定
    for (var i = 0; i < arr.length; i++) {
      // 默认是第一个
      _skuResults.add(1);
    }
  }

  /// 切换获取类别的时候，更新下spu每一项
  _setSkuOptions1() {
    _jSkuOptions1 = jsonDecode(_data[_categoryIndex]["option1"]);
  }

  _reShowMission() {
    var jSkuOptions3 = jsonDecode(_data[_categoryIndex]["option3"]);
    var valuesList = jSkuOptions3["values"];
    valuesList.asMap().keys.map((index) {
      Log.i(index);
      var SKU = valuesList[index]["SKU"];
      if (SKU == skuCode) {
        num car_load = valuesList[index]["car_load"];
        num qty = _qtyLayoutController.number ?? widget.selectDataInfo["qty"];
        num result = qty / car_load;
        // _missionNum = result.ceil();
        // setState(() {
        //   _missionNum = _missionNum;
        //   _taskLayoutController.number = _missionNum;
        // });
        // eventBus.fire(ClickAmountEvent(_missionNum));
      }
    }).toList();
  }

  _onClickSubmit() {
    if (_weightLayoutController.number == 0 && _unit == 2) {
      Tip.show("请输入数量");
      return;
    }
    if (_qtyLayoutController.number == 0) {
      Tip.show("请输入件数");
      return;
    }
    // if (_taskLayoutController.number == 0) {
    //   Tip.show("请输入任务数量");
    //   return;
    // }
    CustomAlertDialog.showConfirmDialog(context,
        content: "确认修改货物信息吗？", confirmText: "确认修改", onConfirm: () {
      var dialog = LoadingDialog(context);
      dialog.show(text: "提交中...");
      var json = _getPostJson();
      Log.i(json);
      var url = WaybillApi.modify;
      dialog.hide();
      Api.submitx(context, url, data: json, progress: false, success: (data) {
        dialog.hide();
        eventBus.fire(RefreshOrderEvent());
        NavigatorUtils.goBack(context);
        Toast.show(context);
      },
          // failTip: "运单已装货完成，无法修改货物信息",
          fail: (response) {
        dialog.hide();
        Tip.show(response.msg);
      });
    });
  }

  dynamic _getPostJson() {
    var json = {};
    json["waybill_no"] = widget.selectDataInfo["waybill_no"];

    json["spu_product_id"] = spuProductId;
    json["sku_code"] = skuCode;

    json["spu_product_name"] = spuProductName == ""
        ? widget.selectDataInfo["spu_product_name"]
        : spuProductName;
    json["sku_option"] = skuOption1.isEmpty
        ? widget.selectDataInfo["sku_option1"]
        : jsonEncode(skuOption1);
    // json["sku_product_id"] = skuProductId == 0
    //     ? widget.selectDataInfo["sku_product_id"]
    //     : skuProductId;
    // json["sku_product_name"] = skuProductName == ""
    // ? widget.selectDataInfo["sku_product_name"]
    // : skuProductName;
    // json["mission_num"] = _taskLayoutController.number > 0
    //     ? _taskLayoutController.number
    //     : widget.selectDataInfo["mission_num"];
    json["unit"] = _unit > 0 ? _unit : widget.selectDataInfo["unit"];
    json["unit_name"] =
        _unitName == "" ? widget.selectDataInfo["unit_name"] : _unitName;

    var weight = _weightLayoutController.number;
    var qty = _qtyLayoutController.number;
    if (_unit == 2) {
      json["weight"] = (weight * 1000).toInt();
    }
    json["qty"] = qty.toInt();
    Log.i(json);
    print(json);
    return json;
  }
}
